﻿/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using MyPhotoIndex.Plugins.WebHost.Security;
using MyPhotoIndex.Plugins.WebHost.VirtualPages;
using System.Reflection;
using MyPhotoIndex.Plugins.WebHost.Properties;

namespace MyPhotoIndex.Plugins.WebHost.RequestHandlers
{
    class GenericRequestHandler : IRequestHandler
    {
        public GenericRequestHandler()
            : base()
        {
        }

        public void Process(HttpListenerRequest request, HttpListenerResponse response)
        {
            string fileName = VirtualPathUtility.GetFileName(request.Url.AbsolutePath);
            if (string.IsNullOrEmpty(fileName) == true)
            {
                fileName = "default.htm";
            }

            string fileExtention = VirtualPathUtility.GetExtension(request.Url.AbsolutePath);
            if (string.Compare(fileExtention, ".mvp", true) == 0)
            {
                VirtualPage.ProcessPage(request, response, fileName);
                return;
            }

            //      string basePath = @"c:\content";
            string basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            basePath = Path.Combine(basePath, "Webcontent");
            string physicalPath = basePath;

            string virtualPath = VirtualPathUtility.GetDirectory(request.Url.AbsolutePath);
            if (string.IsNullOrEmpty(virtualPath) == false)
            {
                virtualPath = virtualPath.Remove(0, 1);
                string convertedPath = virtualPath.Replace('/', Path.DirectorySeparatorChar);
                physicalPath = Path.Combine(basePath, convertedPath);
            }

            string physicalFileName = Path.Combine(physicalPath, fileName);
            response.ContentType = Utils.GetContentTypeFromFileExtention(fileExtention);

            if (File.Exists(physicalFileName) == false)
            {
                ReadFromResource(fileName, request, response);
                return;
            }

            Utils.SetCacheHeadersOneHour(response, File.GetLastWriteTimeUtc(physicalFileName));

            using (FileStream fs = new FileStream(physicalFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                response.ContentLength64 = fs.Length;

                using (Stream output = response.OutputStream)
                {
                    Utils.CopyStreams(fs, output);
                }
            }
        }

        private void ReadFromResource(string fileName, HttpListenerRequest request, HttpListenerResponse response)
        {
            try
            {
                string resourceName = "MyPhotoIndex.Plugins.WebHost.WebContent";
                string filePath = VirtualPathUtility.GetDirectory(request.Url.AbsolutePath);
                if (string.IsNullOrEmpty(filePath) == true)
                {
                    filePath = ".";
                }
                resourceName = resourceName + filePath.Replace('/', '.') + fileName;

                Assembly assembly = Assembly.GetExecutingAssembly();
                using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                {
                    if (stream == null)
                    {
                        Utils.EndResponse(request, response, 404);
                        return;
                    }

                    using (Stream output = response.OutputStream)
                    {
                        Utils.CopyStreams(stream, output);
                    }
                }
            }
            catch (Exception)
            {
                Utils.EndResponse(request, response, 404);
            }
        }
    }
}
